package com.miage.m1.javabrowser.plugins;

import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;

import javax.swing.JPanel;
import javax.swing.JTextArea;

import com.miage.m1.javabrowser.MyLabel;
import com.miage.m1.javabrowser.interfaces.PlugInterface;


public class JarContent extends JPanel implements MouseListener,PlugInterface {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	JarFile jf;
	
	public void initialize(String jarName) {
		Enumeration<JarEntry> e;
		
		try {
			jf = new JarFile(jarName);
			
		} catch (IOException ex) {
			ex.printStackTrace();
		}
		
		e = jf.entries();
				
		while (e.hasMoreElements()){
			ZipEntry nextEntry = (ZipEntry) e.nextElement();
			MyLabel entryName = new MyLabel (nextEntry.getName(),new File(nextEntry.getName()).getAbsolutePath());		
			this.add(entryName);
		}
	}

	public void dirDisplay(String text){	
		this.removeAll();
		File f = new File(text);
		int i;
		File[] tab = f.listFiles();	
		
		for(i=0; i<tab.length;i++){
			MyLabel j = new MyLabel(tab[i].getName(),tab[i].getAbsolutePath());
			this.add(j);
		}
		this.repaint();
		this.revalidate();
	}
	
	public void objectDisplay(String text){
		BufferedReader fr;
		String text2 = null;
		
		try {
			
			fr = new BufferedReader(new FileReader(text));		
			String ligne;
			while((ligne = fr.readLine())!=null){
				
				text2= text2 + ligne;
				
			}
			
		} catch (Exception e) {			
			e.printStackTrace();
		}
		
		JTextArea jt = new JTextArea ( text2);
		this.add(jt);		
		this.repaint();
		this.revalidate();
	}

	
	@Override
	public void mouseClicked(MouseEvent e) {
		ZipEntry trouve;
		String text=((MyLabel) e.getSource()).getText();
		Enumeration<?> en = jf.entries();
		trouve=null;
		
		while (en.hasMoreElements()){
			
			ZipEntry nextEn = (ZipEntry) en.nextElement();
			
			if (nextEn.getName().equals(text)){
				 trouve = nextEn;
				 
			}
					
		}
		if (trouve !=null){
			if (trouve.isDirectory()){
				
				dirDisplay(trouve.getName());
				
			}
			else if(trouve.getName().endsWith(".class")){
				
				objectDisplay(trouve.getName());
				
			}
		}
	}

	@Override
	public void mouseEntered(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		
	}

	
}
